/*
 * Copyright (c) 2025 Industrial Software Feature Database
 */
package com.comac.ins.isfd.rpc.xuelang;

import cn.hutool.core.util.ObjectUtil;
import com.comac.ins.common.core.exception.base.BaseException;
import com.comac.ins.common.core.utils.SpringUtils;
import com.comac.ins.isfd.rpc.xuelang.bo.XueLangRenderBo;
import com.comac.ins.isfd.rpc.xuelang.bo.XueLangRenderResultBo;
import com.comac.ins.isfd.rpc.xuelang.bo.XueLangResponseBo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
public class XueLangStaticRpcUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();


    public static <T> T parseObject(String text, Class<T> clazz) {
        if (com.comac.ins.common.core.utils.StringUtils.isEmpty(text)) {
            return null;
        }
        try {
            return objectMapper.readValue(text, clazz);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static String toJsonString(Object object) {
        if (ObjectUtil.isNull(object)) {
            return null;
        }
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }

    public static String render(XueLangRenderBo xueLangRenderBo) {
        String apiUrl = "http://192.168.2.86/d3-common-api/api/render-url";
        XueLangResponseBo xueLangResponseBo = XueLangStaticRestTemplateUtils.post(apiUrl, xueLangRenderBo);
        if (xueLangResponseBo.getData() == null) {
            log.error("调用雪浪渲染接口返回的data值为空,apiUrl：{}, 入参为：{}", apiUrl, toJsonString(xueLangRenderBo));
            throw new BaseException("数据库建模后，获取数据库建模配置的data值为空");
        }
        XueLangRenderResultBo xueLangRenderResultBo = parseObject(xueLangResponseBo.getData(), XueLangRenderResultBo.class);
        if (xueLangRenderResultBo == null) {
            log.error("调用雪浪渲染接口返回的data值为空,apiUrl：{}, 入参为：{}", apiUrl, toJsonString(xueLangRenderBo));
            throw new BaseException("数据库建模后，获取数据库建模配置的data值为空");
        }
        String renderUrl = xueLangRenderResultBo.getRenderUrl();
        if (StringUtils.isBlank(renderUrl)) {
            log.error("调用雪浪渲染接口返回的renderUrl值为空,apiUrl：{}, 入参为：{}", apiUrl, toJsonString(xueLangRenderBo));
            throw new BaseException("数据库建模后，获取数据库建模配置的data值为空");
        }
        return renderUrl;
    }
}
